const express = require('express');
const router = express.Router();
const User = require('../models/users');
const jsonwebtoken = require('jsonwebtoken');
const {secret} = require('../config');
const saltRounds = 10;
const bcrypt = require('bcrypt');

/* GET users listing. */
router.get('/', function (req, res, next) {
    res.send('respond with a resource');
});

router.post('/signup', function (req, res) {
    const {username, password, preference} = req.body;
    if (!User.validateName(username)) {
        return res.json({
            error: {
                message: "请输入正确的邮箱"
            }
        });
    }
    bcrypt.hash(password, saltRounds, function (err, hash) {
        if (err) return new Error(err);
        User.findOrCreate({where: {username: username}, defaults: {password: hash, preference: preference}})
            .spread((user, created) => {
                if (created) {
                    res.cookie('token', jsonwebtoken.sign({username: username}, secret, {expiresIn: 3000}), {httpOnly: true});
                    res.json({
                        success: {
                            message: '注册成功'
                        }
                    });
                } else {
                    res.json({
                        error: {
                            message: "邮箱已被注册"
                        }
                    });
                }
            });
    });
});

router.post('/signin', function (req, res, next) {
    const {username, password} = req.body;
    User.findOne({where: {username: username}}).then(async (user) => {
        if (user) {
            const authenticated = await user.checkPassword(password);
            if (authenticated) {
                res.cookie('token', jsonwebtoken.sign({username: username}, secret, {expiresIn: 3000}), {httpOnly: true});
                res.json({
                    success: {
                        message: '登陆成功'
                    }
                });
            } else {
                res.json({
                    error: {
                        message: '账号或密码错误'
                    }
                })
            }
        } else {
            res.json({
                error: {
                    message: '账号或密码错误'
                }
            })
        }
    })
});

router.post('/signout', function (req, res, next) {
    if (req.user) {
        res.clearCookie('token');
        res.json({
            success: {
                message: '注销成功'
            }
        })
    } else {
        res.json({
            error: {
                message: '未登陆'
            }
        })
    }
});

module.exports = router;
